package com.eightbears.beboy.ui.user.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.BuyVIPListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.ViewVipTitleBar;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ProductsEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.entity.status.Status_Products;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_PAGE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PRODUCTS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_USERDATA;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.EVENT_BUY_VIP_SUCCESS;

/**
 * 我的特权页面
 */
public class ByVipActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener
        , SwipeRefreshLayout.OnRefreshListener {

    public static final String PARAMS_BUY_VIP = "vipEntity";
    public static final String EVENT_UPDATE_USER_STATUS = "vipUpdate";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.vvt_title_bar)
    ViewVipTitleBar vvt_title_bar;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;

    private UserEntity mUserEntity;

    private BuyVIPListAdapter mBuyVIPListAdapter;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_by_vip);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }


    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mUserEntity = SPUtil.getUser();

        swipeLayout.setRefreshing(true);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(ByVipActivity.this));
        mBuyVIPListAdapter = new BuyVIPListAdapter();
        mBuyVIPListAdapter.setOnLoadMoreListener(this);
        mBuyVIPListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//添加加载动画
        rv_list.setAdapter(mBuyVIPListAdapter);
        vvt_title_bar.setUserNickNameText(mUserEntity.getData().getNickname());
        vvt_title_bar.setVipDateText("");
        vvt_title_bar.setUserHeadImageResource(mUserEntity.getData().getCover());

        if (mUserEntity.getData().getVip_level() > 0) {
            if (mUserEntity.getData().getVip_validity() != null) {
                vvt_title_bar.setVipDateText(CommonUtils.TimeStamp2Date(mUserEntity.getData().getVip_validity(), "yyyy-MM-dd"));
            }
            if (mUserEntity.getData().getVip_level() == 1) {
                vvt_title_bar.setVipBGImageResource(R.mipmap.vip_1);
                vvt_title_bar.setVipImageResource(R.mipmap.icon_new_vip1);
            } else if (mUserEntity.getData().getVip_level() == 2)
                vvt_title_bar.setVipBGImageResource(R.mipmap.vip_2);
            vvt_title_bar.setVipImageResource(R.mipmap.icon_new_vip2);
        } else {
            vvt_title_bar.setVipBGImageResource(R.mipmap.vip_0);
        }

        if (mUserEntity.getData().getPoints() != null) {
            if (mUserEntity.getData().getPoints().getLevel() == 1) {
                vvt_title_bar.setLevelResource(R.mipmap.icon_level_one);
            } else if (mUserEntity.getData().getPoints().getLevel() == 2) {
                vvt_title_bar.setLevelResource(R.mipmap.icon_level_two);
            } else if (mUserEntity.getData().getPoints().getLevel() == 3) {
                vvt_title_bar.setLevelResource(R.mipmap.icon_level_three);
            } else if (mUserEntity.getData().getPoints().getLevel() == 4) {
                vvt_title_bar.setLevelResource(R.mipmap.icon_level_four);
            } else if (mUserEntity.getData().getPoints().getLevel() == 5) {
                vvt_title_bar.setLevelResource(R.mipmap.icon_level_five);
            }
        }
    }

    @Override
    protected void initData() {
        getShopList();
    }

    @Override
    protected void initEvent() {
        vvt_title_bar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //侧滑删除实力化
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        mBuyVIPListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ProductsEntity productsEntity = (ProductsEntity) adapter.getData().get(position);
                startLocalActivity(ByVipActivity.this, PaymentActivity.class, PARAMS_BUY_VIP, productsEntity);
            }
        });
    }

    /**
     * 获取数据
     */
    public void getShopList() {
        OkHttpUtils.get().url(URL_PRODUCTS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams(PARAM_URL_PAGE, "1")
                .addParams(PARAM_URL_SIZE, PARAMS_PAGE_SIZE)
                .addParams("category", "2")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                Status_Products status_products = GsonUtil.fromJson(response, Status_Products.class);
                if (CONNECTION_STATUS_SUCCESS.equals(status_products.getStatus_code())) {
                    isEnd = status_products.getData().is_end();
                    if (page == 1)
                        mBuyVIPListAdapter.setNewData(status_products.getData().getList());
                    else {
                        mBuyVIPListAdapter.addData(status_products.getData().getList());
                        mBuyVIPListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ByVipActivity.this, status_error);
            }

        });
    }

    /**
     * 获取用户数据
     */
    public void getUserinfo() {
        //获取token
        OkHttpUtils.get().url(URL_RESET_USERDATA + mUserEntity.getData().getUser_id())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                UserInfoEntity userInfoEntity = GsonUtil.fromJson(response, UserInfoEntity.class);
                KLog.e(response);
                if (CONNECTION_STATUS_SUCCESS.equals(userInfoEntity.getStatus_code())) {
                    mUserEntity.getData().setVip_level(userInfoEntity.getData().getVip_level());
                    mUserEntity.getData().setVip_validity(userInfoEntity.getData().getVip_validity());
                    SPUtil.putUser(mUserEntity);
                    EventBus.getDefault().post(EVENT_UPDATE_USER_STATUS);
                    initView();
                    getShopList();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ByVipActivity.this, status_error);
            }

        });
    }

    @Override
    public void onRefresh() {
        mBuyVIPListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mBuyVIPListAdapter.getData().clear();
                getShopList();
                mBuyVIPListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);

    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mBuyVIPListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getShopList();
                    } else {
                        isErr = true;
                        Toast.makeText(ByVipActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mBuyVIPListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_BUY_VIP_SUCCESS:
                getUserinfo();
                break;
        }
    }
}
